package com.hxkj.shiro;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * shiro过滤器
 * <p>
 * Created by chenwei on 2018/5/28.
 */
@Slf4j
public class ServiceAuthFilter extends AccessControlFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

        HttpServletRequest req = (HttpServletRequest) request;
        // 从header中取得token值
        String token = req.getHeader("accessToken");
        // 从参数中获取
        if (StringUtils.isEmpty(token)) {
            token = req.getParameter("accessToken");
        }
        // 取得用户账号
        if (StringUtils.isEmpty(token)) {
            onAjaxAuthFail(response);
            return true;
        }
        StatelessToken statelessToken = new StatelessToken(null, token);
        try {
            // 委托Realm验证
            getSubject(request, response).login(statelessToken);
        } catch (Exception e) {
            onAjaxAuthFail(response);
            return true;
        }
        return true;
    }


    /**
     * 封装返回值
     *
     * @param resp
     * @throws IOException
     */
    private void onAjaxAuthFail(ServletResponse resp) throws IOException {
        HttpServletResponse response = (HttpServletResponse) resp;
        JSONObject json = new JSONObject();
        json.put("msg", "登录状态过期");
        json.put("code", 400);
        response.setStatus(HttpServletResponse.SC_REQUEST_TIMEOUT);
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(json.toString());
    }
}
